<?php

class Admin_Model_City {

    private $_dbtable;

    public function __construct() {
        $this->_dbtable = new Admin_Model_DbTable_City();
    }

    /**
     * 
     * @return type
     */
    public function fetchAll() {
        $select = $this->_dbtable->select();
        return $this->_dbtable->fetchAll($select);
    }

    /**
     * 
     * @param type $data
     * @return type
     */
    public function createNewCity($data) {
        return $this->_dbtable->insert($data);
    }

    /**
     * 
     * @param type $data
     * @param type $id
     * @return type
     */
    public function updateCity($data, $id) {
        return $this->_dbtable->update($data, "id = $id");
    }

    /**
     * 
     * @param type $id
     * @return type
     */
    public function getCityById($id) {
        $select = $this->_dbtable->select();
        $select->where("id = $id");
        return $this->_dbtable->fetchAll($select);
    }

    /**
     * Just city by id
     */
    public function getCityArray($id, $formated) {
        $cityById = $this->getCityById($id);
        $array = array(
            'id' => $cityById[0]['id'],
            'name' => $cityById[0]['name'],
            'state_id' => $cityById[0]['state_id'],
        );
        if ($formated) {
            $array = array('city' => $array);
        }
        return $array;
    }

    /**
     * City by id and it's state
     * @param type $id
     * @return type
     */
    public function getCityWithStateArray($id, $formated) {
        $stateDb = new Admin_Model_State();
        $justCityArray = $this->getCityArray($id, $formated);
        $justStateArray = $stateDb->getJustStateArray($justCityArray['state_id'], $formated);
        if($formated){
            $array = array('city' => $justCityArray, 'state' => $justStateArray);
        }else{
            $array = array($justCityArray,$justStateArray);
        }
        return $array;
    }

    /**
     * 
     * @param type $id
     * @param type $formated
     */
    public function getAllCityWithStateArray($formated = true) {
        $fetchAll = $this->fetchAll();
        $array = array();
        foreach ($fetchAll as $city) {
            $cityWithStateArray = $this->getCityWithStateArray($city['id'], false);
            array_push($array, $cityWithStateArray);
        }
        return $array;
    }

    /**
     * 
     * @param type $id
     * @param type $formated
     */
    public function getAllCityArray($formated = true) {
        $fetchAll = $this->fetchAll();
        $array = array();
        foreach ($fetchAll as $city) {
            $cityArray = $this->getCityArray($city['id'], $formated);
            array_push($array, $cityArray);
        }
        return $array;
    }

}

